package cloud.lysky.order.service.impl;


import cloud.lysky.order.domain.Order;
import cloud.lysky.order.feign.ProductFeignClient;
import cloud.lysky.order.feign.ThirdPartyFeignClient;
import cloud.lysky.order.service.IOrderService;
import cloud.lysky.product.domain.Product;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class OrderServiceImpl implements IOrderService {
    private final ProductFeignClient productFeignClient;
    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    private final LoadBalancerClient loadBalancerClient;
    private final ThirdPartyFeignClient thirdPartyFeignClient;

    @Override
    public Order createOrder(Long userId, Long productId) {
        Order order = new Order();
        Product product = getProductFromRemoteWithFeign(productId);
        order.setId(System.currentTimeMillis());
        order.setTotalAmount(calculateTotalAmount(product));
        order.setUserId(userId);
        order.setUserName("LuoLiYou");
        order.setAddress("贵州省遵义市绥阳县");
        order.setProducts(List.of(product));
        return order;
    }

    @Override
    public String fetchFunnyJoke() {
        return thirdPartyFeignClient.fetchFunny();
    }

    protected BigDecimal calculateTotalAmount(Product product) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        totalAmount = product.getPrice().multiply(BigDecimal.valueOf(product.getNum()));
        return totalAmount;
    }

    protected Product getProductFromRemote(Long productId) {
        // 查询远程Product Service
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        if (instances.isEmpty()) {
            log.error("Product Service is not available.");
            return null;
        }
        ServiceInstance instance = instances.stream().findAny().get();
        // 获取 productId 对应的 Product
        String productServiceUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/api/product/" + productId;
        log.warn("Get product from Product Service: {}", productServiceUrl);
        return restTemplate.getForObject(productServiceUrl, Product.class);
    }

    // 采用负载均衡的方式获取 Product
    protected Product getProductFromRemoteWithLoadbalancer(Long productId) {
        // 查询远程Product Service
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        if (instance == null) {
            log.error("Product Service is not available.");
            return null;
        }
        // 获取 productId 对应的 Product
        String productServiceUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/api/product/" + productId;
        log.warn("Get product from Product Service: {}", productServiceUrl);
        return restTemplate.getForObject(productServiceUrl, Product.class);
    }

    // 基于负载均衡注解的方式获取 Product
    // 采用负载均衡的方式获取 Product
    protected Product getProductFromRemoteWithLoadbalancerAnnotation(Long productId) {
        // service-product会被动态替换为实际存在的服务地址
        String productServiceUrl = "http://service-product/api/product/" + productId; // 注意此处是使用了@LoadBalanced 注解的 RestTemplate
        log.warn("Get product from Product Service: {}", productServiceUrl);
        return restTemplate.getForObject(productServiceUrl, Product.class);
    }

    // 采用 Feign 方式获取 Product
    protected Product getProductFromRemoteWithFeign(Long productId) {
        // 注意此处是使用了 FeignClient 注解的 RestTemplate
        return productFeignClient.getProductById(productId);
    }
}
